#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#define MAXLINE 1024
#define CLIENT_FIFO "client.fifo"
#define SERVER_FIFO "server.fifo"

 

//允许用户读、用户写、组成员读和其他用户读，

#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

 

void client(int ,int);

 

int main(int argc, char **argv)
{

    int    readfd, writefd;

 

    //创建客户端的FIFO
    if((mkfifo(CLIENT_FIFO, FILE_MODE) < 0) && (errno != EEXIST))
    {

        printf("can't create %s", CLIENT_FIFO);
        exit(0);
    }

 

    //注意打开来读和打开来写的顺序，否则客户端会与服务器互相阻塞，构成死锁

    //打开服务器的FIFO
    writefd = open(SERVER_FIFO, O_WRONLY, 0);
    if (writefd < 0)
    {
           printf("open serverfd  failure\n");

    }
    printf("serverfd open\n");

    //打开客户端的FIFO
    readfd = open(CLIENT_FIFO, O_RDONLY, 0);
    if(readfd<0)
    {
           printf("open clientfd failure\n");

    }
    printf("clientfd open\n");
 
    client(readfd, writefd);
    
    //删除客户端的FIFO

    unlink(CLIENT_FIFO);
    exit(0);

}

 

//客户端函数

void client(int readfd,int writefd)
{

    size_t      len;
    ssize_t     n;
    char        buff[MAXLINE];

 

    //从标准输入流获文件名

    fgets(buff, MAXLINE, stdin);

    //获取文本长度

    len = strlen(buff);

    //去掉输入的回车

    if (buff[len-1] == '\n')
    len --;

 

   //将文件名发送给服务器

   write(writefd, buff, len);

    //接收服务器返回的数据

   while ((n = read(readfd, buff, MAXLINE)) > 0)
   write(STDOUT_FILENO, buff, n);

}

